// utils/network-helper.js - 网络连接辅助工具

/**
 * 检查手机和电脑是否在同一网络
 */
function checkNetworkConnection() {
  return new Promise((resolve) => {
    // 获取网络信息
    wx.getNetworkType({
      success: (res) => {
        console.log("网络类型:", res.networkType);
        resolve({
          networkType: res.networkType,
          isConnected: res.networkType !== "none",
        });
      },
      fail: () => {
        resolve({
          networkType: "unknown",
          isConnected: false,
        });
      },
    });
  });
}

/**
 * 获取本机IP地址建议
 */
function getIPSuggestions() {
  return [
    {
      name: "常见局域网IP段",
      ips: ["192.168.1.x", "192.168.0.x", "192.168.139.x", "10.0.0.x"],
    },
    {
      name: "检查方法",
      steps: [
        "1. 电脑打开cmd，输入 ipconfig",
        "2. 查看 '以太网适配器' 或 'WiFi适配器' 的IPv4地址",
        "3. 确保手机和电脑连接同一WiFi",
        "4. 在config/api.js中更新IP地址",
      ],
    },
  ];
}

/**
 * 网络故障排除指南
 */
function getTroubleshootingGuide() {
  return {
    title: "手机端连接本地服务器故障排除",
    steps: [
      {
        step: 1,
        title: "检查网络连接",
        actions: [
          "确保手机和电脑连接同一WiFi网络",
          "检查电脑防火墙是否阻止8082端口",
          "尝试在手机浏览器访问 http://[电脑IP]:8082",
        ],
      },
      {
        step: 2,
        title: "获取正确的IP地址",
        actions: [
          "Windows: 打开cmd，输入 ipconfig",
          "Mac: 打开终端，输入 ifconfig",
          "查找 '以太网适配器' 或 'WiFi适配器' 的IPv4地址",
          "通常是 192.168.x.x 或 10.x.x.x 格式",
        ],
      },
      {
        step: 3,
        title: "配置服务器",
        actions: [
          "确保本地服务器监听 0.0.0.0:8082 而不是 127.0.0.1:8082",
          "检查服务器是否允许跨域请求",
          "确认服务器正在运行且端口8082可访问",
        ],
      },
      {
        step: 4,
        title: "更新小程序配置",
        actions: [
          "在 config/api.js 中更新正确的IP地址",
          "重新编译小程序",
          "清除小程序缓存后重新测试",
        ],
      },
    ],
  };
}

module.exports = {
  checkNetworkConnection,
  getIPSuggestions,
  getTroubleshootingGuide,
};
